package com.cn.server.tcp;

import com.cn.common.core.codc.RequestDecoder;
import com.cn.common.core.codc.ResponseEncoder;
import com.cn.common.module.ModuleId;
import com.cn.common.module.chat.ChatCmd;
import com.cn.common.module.login.UserCmd;
import com.cn.server.handler.mobile.LoginHandler;
import com.cn.server.handler.mobile.LogoutHandler;
import com.cn.server.handler.mobile.SingleChatHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

/**
 * netty服务端
 */
@Component
public class Server {

    private MessageDispatcher messageDispatcher = new MessageDispatcher();


    public Server registerHandlers() {
        messageDispatcher.register(ModuleId.USER, UserCmd.LOGIN, new LoginHandler());
        messageDispatcher.register(ModuleId.USER, UserCmd.LOGOUT, new LogoutHandler());
        messageDispatcher.register(ModuleId.CHAT, ChatCmd.PRIVATE_CHAT, new SingleChatHandler());
        return this;
    }
    private int port;

    public Server setPort(int port) {
        this.port = port;
        return this;
    }
    /**
     * 启动
     */
    public void start() {

        // 服务类
        ServerBootstrap b = new ServerBootstrap();

        // 创建boss和worker
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 设置循环线程组事例
            b.group(bossGroup, workerGroup);

            // 设置channel工厂
            b.channel(NioServerSocketChannel.class);

            // 设置管道
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new RequestDecoder());
                    ch.pipeline().addLast(new ResponseEncoder());
                    ch.pipeline().addLast(new ServerHandler(messageDispatcher));
                }
            });

            b.option(ChannelOption.SO_BACKLOG, 2048);// 链接缓冲池队列大小

            // 绑定端口
            b.bind(10103).sync();
            System.out.println("simple mobile chat start!!!");
        } catch (Exception e) {
            e.printStackTrace();
        } /*finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }*/
    }

}
